package com.sigmazero13.MKDummy.components;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.sigmazero13.MKDummy.models.ImageValuePair;

public class ImageSelector<T> extends LinearLayout {
	
	private Context mContext;
	private T curValue;
	
	public ImageSelector(Context context) {
		super(context);
		mContext = context;
		commonSetup();
	}

	
	public ImageSelector(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		commonSetup();
	}
	
	
	private void commonSetup() {
		this.setOrientation(LinearLayout.HORIZONTAL);
		this.setGravity(Gravity.CENTER_HORIZONTAL);
	}
	
	
	public T getSelectedValue() {
		return curValue;
	}
	
	
	public void setImageValues(List<ImageValuePair<T>> imageValues) {
		this.removeAllViews();
		curValue = null;
		
		for (ImageValuePair<T> imageValue : imageValues) {
			ImageSelection<T> selection = new ImageSelection<T>(mContext);
			selection.setImageBitmap(imageValue.getImage());
			selection.setValue(imageValue.getValue());
			selection.setPadding(15, 10, 15, 10);
			
			if (curValue == null) {
				selection.setSelected(true);
				curValue = imageValue.getValue();
			}
			
			selection.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (v instanceof ImageSelection) {
						@SuppressWarnings("unchecked")
						ImageSelection<T> sel = (ImageSelection<T>)v;
						
						selectValue(sel.getValue());
					}
				}
			});
			
			this.addView(selection);
		}
	}
	
	
	private void selectValue(T value) {
		curValue = value;
		for (int i = 0; i < this.getChildCount(); i++) {
			View v = this.getChildAt(i);
			if (v instanceof ImageSelection) {
				@SuppressWarnings("unchecked")
				ImageSelection<T> sel = (ImageSelection<T>)v;
				
				sel.setSelected(value.equals(sel.getValue()));
			}
		}
	}
	
	
	private class ImageSelection<V extends T> extends ImageView {
		private V value;

		public ImageSelection(Context context) {
			super(context);
		}
		
		public void setValue(V value) {
			this.value = value;
		}
		
		public V getValue() {
			return value;
		}
		
		public void setSelected(boolean selected) {
			if (selected) {
				this.setBackgroundColor(Color.LTGRAY);
			} else {
				this.setBackgroundColor(Color.TRANSPARENT);
			}
		}
		
	}
	
}
